package com.boyou.sytzc.data.database.table;

import android.content.Context;

import com.boyou.sytzc.data.entity.GeoLocationInfoEntity;
import com.boyou.sytzc.data.entity.GeoLocationInfoEntity_;
import com.boyou.sytzc.core.appctx.AppApplication;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

import io.objectbox.Box;

/**
 * Created by mrper on 17-7-24.
 * Geo Location DB
 */
public class GeoLocationDB {

    private static GeoLocationDB geoDB;

    public static GeoLocationDB getInstance(Context context) {
        if (geoDB == null) {
            synchronized (GeoLocationDB.class) {
                geoDB = new GeoLocationDB(context);
            }
        }
        return geoDB;
    }

    private final Box<GeoLocationInfoEntity> box;

    private GeoLocationDB(Context context) {
        box = Objects.requireNonNull(((AppApplication) context.getApplicationContext()).getBoxStore()).boxFor(GeoLocationInfoEntity.class);
    }

    public long put(GeoLocationInfoEntity item) {
        return box.put(item);
    }

    public GeoLocationDB put(GeoLocationInfoEntity... items) {
        box.put(items);
        return this;
    }

    public GeoLocationDB put(Collection<GeoLocationInfoEntity> items) {
        box.put(items);
        return this;
    }

    public List<GeoLocationInfoEntity> findAll() {
        return box.getAll();
    }

    public List<GeoLocationInfoEntity> findUnUpload() {
        List<GeoLocationInfoEntity> result = box.query().equal(GeoLocationInfoEntity_.isUpload, false).build().find();
        if (result.size() > 1) {
            Collections.sort(result, (o1, o2) -> {
                assert o1.createTime != null;
                assert o2.createTime != null;
                return (int) (o1.createTime.getTime() - o2.createTime.getTime());
            });
        }
        return result;
    }

    public GeoLocationDB removeAllUploaded() {
        List<GeoLocationInfoEntity> all = box.query().equal(GeoLocationInfoEntity_.isUpload, true).build().find();
        box.remove(all);
        return this;
    }

    public GeoLocationDB clear() {
        box.removeAll();
        return this;
    }

}
